package com.zidian.study.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.EvalutaCustomAdapter;
import com.zidian.study.bean.EvaluateCustomBean;
import com.zidian.study.bean.EvaluateTeacherBean;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ProgressBarBlackUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/4 0004.
 * <p/>
 * 自定义评价
 */
public class EvaluateCustomActivity extends ToolBarActivity {


    boolean isLoading;
    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.swipe_refresh_widget)
    SwipeRefreshLayout swipeRefreshWidget;
    @Bind(R.id.issue_edit)
    EditText issueEdit;
    @Bind(R.id.issue_confirm)
    Button issueConfrim;
    private List<EvaluateCustomBean.DataBean.ListBean> data = new ArrayList<>();
    private EvalutaCustomAdapter adapter;
    private Handler handler = new Handler();
    private EvaluateTeacherBean.DataBean teacherMessage = new EvaluateTeacherBean.DataBean();
    private int startrow = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_interaction_ask_detail);
        ButterKnife.bind(this);
        setTitle("自定义评价");
        teacherMessage = (EvaluateTeacherBean.DataBean) getIntent().getSerializableExtra("teacher");
        getData(startrow + "");
        intiView();

    }

    public void intiView() {
        adapter = new EvalutaCustomAdapter(this, data, teacherMessage);
        swipeRefreshWidget.setColorSchemeResources(R.color.green);
        swipeRefreshWidget.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshWidget.setRefreshing(true);
            }
        });
        swipeRefreshWidget.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        data.clear();
                        startrow = 1;
                        getData(startrow + "");
                    }
                }, 2000);
            }
        });


        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.d("test", "StateChanged = " + newState);


            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("test", "onScrolled");

                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = swipeRefreshWidget.isRefreshing();
                    if (isRefreshing) {
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startrow++;
                                getData(startrow + "");
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });


        issueConfrim.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                evaluateCustom();
            }
        });


    }


    /**
     * 获取测试数据
     */
    private void getData(String startrow) {
        String loginUrl = Constant.URL_TEACHER + "EvaluateTeacher/CustomEvaluation";
        HashMap<String, String> map = new HashMap<>();
        map.put("startrow", startrow);
        map.put("pageSize", "10");
        map.put("teacherId", teacherMessage.getTeacherId());
        map.put("operatorType", "学生");
        map.put("operatorId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));

        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("E", e.toString());
                swipeRefreshWidget.setRefreshing(false);
            }

            @Override
            public void onResponse(String response, int id) {
                swipeRefreshWidget.setRefreshing(false);
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        isLoading = true;
                        adapter.setHasMore(false);
                        adapter.notifyDataSetChanged();
                        adapter.notifyItemRemoved(adapter.getItemCount());
                        return;
                    }

                } catch (JSONException e) {

                }

                Gson gson = new Gson();
                EvaluateCustomBean model = gson.fromJson(response, EvaluateCustomBean.class);
                if (model.isSuccess()) {
                    if (model.getData().getList().size() < 10) {
                        isLoading = true;
                        adapter.setHasMore(false);
                    } else {
                        isLoading = false;
                        adapter.setHasMore(true);
                    }

                    data.addAll(model.getData().getList());
                    adapter.setEvaluateCustomCount(model.getData().getEvaluateNum());
                    adapter.notifyDataSetChanged();
                    swipeRefreshWidget.setRefreshing(false);
                    adapter.notifyItemRemoved(adapter.getItemCount());
                }
            }
        });
    }

    private void evaluateCustom() {

        //由于公用一个界面所以id就不再修改适应了

        if (issueEdit.getText().toString().length() == 0) {
            Snackbar.make(mRecyclerView,"请输入回复内容！",Snackbar.LENGTH_SHORT).show();
            return;
        }

        String loginUrl = Constant.URL_TEACHER + "ToEvaluateOthers/CustomEvaluationColleagues";
        HashMap<String, String> map = new HashMap<>();
        map.put("role", "student");
        map.put("appraiserId", GetUserInfo.getStudentId(context));
        map.put("byEvaluatePersonId", teacherMessage.getTeacherId());
        map.put("evaluationContent", issueEdit.getText().toString().trim());
        map.put("token", GetUserInfo.getToken(context));
        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("E", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        Snackbar.make(mRecyclerView,"获取问题列表失败！",Snackbar.LENGTH_SHORT).show();
                        return;
                    } else {
                        issueEdit.setText("");
                        Snackbar.make(mRecyclerView,"评论成功！",Snackbar.LENGTH_SHORT).show();
                        data.clear();
                        startrow = 1;
                        getData(startrow + "");
                        mRecyclerView.scrollToPosition(data.size());
                    }

                } catch (JSONException e) {

                }

            }
        });

    }

}
